package com.hjw.controller.adm;

import cn.dev33.satoken.annotation.SaCheckRole;
import cn.dev33.satoken.util.SaResult;
import com.hjw.dao.LargeFileDao;
import com.hjw.entity.Hot;
import com.hjw.entity.LargeFile;
import com.hjw.service.HotService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author Administrator
 * @创建时间：2025-04-22
 * @文件名称：satoken_sobuk - com.hjw.controller.adm
 */
@Slf4j
@SaCheckRole("adm")
@RestController
@RequestMapping("/api/adm/hot")
public class AdmHotController {

    @Autowired
    private HotService hotService;
    @Autowired
    private LargeFileDao largeFileDao;

    @GetMapping("/findAll") // /api/adm/hot/findAll
    public SaResult findAll() {
        return SaResult.get(200, "查询成功", hotService.findAll());
    }

    @GetMapping("/findById/{id}") // /api/adm/hot/findById/{id}
    public SaResult findById(@PathVariable("id") Integer id) {
        Map<String, Object> map = new HashMap<>(1);
        map.put("id", id);
        Hot hot = hotService.findById(id);
        return SaResult.get(200, "查询成功", hot);
    }

    @PostMapping("/addOrUpdate") // /api/adm/hot/addOrUpdate
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public SaResult addOrUpdate(@RequestParam Map<String, Object> map,@RequestParam(value = "mypic", required = false) MultipartFile myfile) {
        log.info("修改信息：{}" , map);
        try {
            log.info("修改信息：{}",myfile);
            //第一种情况，为修改图片，修改图片必须上传原图片id
            if (myfile != null && !myfile.isEmpty() && map.get("picture")!=null && !map.get("picture").toString().isEmpty()){
                LargeFile largeFile = new LargeFile();
                //获取新图片的uuid信息
                UUID uuid = UUID.randomUUID();
                //截取新图片的id
                String newImageId = uuid.toString().replace("-", "");

                String picture = map.get("picture").toString();
                //修改前先删除原图片
                largeFileDao.delete(picture);
                largeFile.setId(newImageId);
                largeFile.setFilename(myfile.getOriginalFilename());
                try {
                    largeFile.setContent(myfile.getBytes());
                } catch (IOException e) {
                    log.error("修改轮播图广告图失败");
                    throw new RuntimeException("修改轮播图广告图失败");
                }
                int add = largeFileDao.add(largeFile);
                if (add == 0){
                    throw new RuntimeException("修改轮播图广告图失败");
                }
                map.put("picture", newImageId);
            }

            if(Integer.parseInt(map.get("id").toString()) != 0){
                if (map.get("picture")!=null && map.get("picture").toString().isEmpty()){
                    map.remove("picture");
                }
                int i = hotService.update(map);
                if (i == 0){
                    throw new RuntimeException("更新失败");
                }
                return SaResult.get(200, "更新成功", map.get("id"));
            }

            if (myfile == null || myfile.isEmpty()){
                return SaResult.get(-200,  "图片不能为空", map.get("id"));
            }
            //第二种情况，为添加图片，并且是新增的轮播广告信息 关键判断：Integer.parseInt(map.get("id").toString()) == 0
            if (!myfile.isEmpty() && map.get("id") != null && Integer.parseInt(map.get("id").toString()) == 0){
                LargeFile largeFile = new LargeFile();
                //获取新图片的uuid信息
                UUID uuid = UUID.randomUUID();
                //截取新图片的id
                String newImageId = uuid.toString().replace("-", "");
                largeFile.setId(newImageId);
                largeFile.setFilename(myfile.getOriginalFilename());
                largeFile.setContent(myfile.getBytes());
                int imgAdd = largeFileDao.add(largeFile);
                Hot hot = new Hot();
                hot.setMemo(map.get("memo").toString());
                hot.setPicture(newImageId);
                hot.setHot(Integer.parseInt(map.get("hot").toString()));
                hot.setType(Integer.parseInt(map.get("type").toString()));
                int hotAdd = hotService.add(hot);
                if (imgAdd == 0 || hotAdd == 0){
                    return SaResult.get(-200, "添加失败", map.get("id"));
                }
                return SaResult.get(200, "添加成功", hot.getId());
            }
        } catch (IOException e) {
            log.error("修改轮播图广告图失败:{}",e.getMessage());
            throw new RuntimeException("修改轮播图广告图失败");
        }
        return SaResult.get(200, "添加成功", map.get("id"));
    }

    @GetMapping("/delete/{id}") // /api/adm/hot/delete/{id}
    public SaResult delete(@PathVariable("id") Integer id) {
        log.info("删除id:{}", id);
        Hot hot = hotService.findById(id);
        if (hot == null){
            return SaResult.get(-200, "删除失败", id);
        }
        String picture = hot.getPicture();
        int delete = largeFileDao.delete(picture);
        if (delete == 0){
            return SaResult.get(-200, "删除失败", id);
        }
        int i = hotService.delete(id);
        if (i == 0){
            return SaResult.get(-200, "删除失败", id);
        }
        return SaResult.get(200, "删除成功", id);
    }


}
